<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Cart;
use app\model\Member;
use app\model\Goods;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class CartController extends Base
{
    public function list()
    {
        $cart = new Cart;
        $data = $cart->getlist();
        return $this->json(['data' => $data]);
    }
    public function exportExcel()
    {
        $form_data = input('post.form_data');
        $type =  input('post.type');
        $data =  json_decode($form_data, true);

        // 创建 Spreadsheet 对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $sheet->setTitle('报价单');; //设置当前工作表标题。

        $sheet->getDefaultColumnDimension()->setWidth(20);
        //合并
        $sheet->mergeCells('A1:H2'); //合并为一个单元格
        $sheet->setCellValue('A1', '佛山市清科新型建材有限公司');
        $sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)
            ->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getColumnDimension('A1')->setWidth(200);
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(18); //将B1单元格设置为粗体字

        $sheet->mergeCells('A3:H3'); //合并为一个单元格
        $sheet->setCellValue('A3', '地址：佛山市三水区西南街道洲边金祥二路3号05厂房      联系人:');
        $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('A4:C4'); //合并为一个单元格
        $sheet->setCellValue('A4', '日期：' . date('Y-m-d'));
        $sheet->getStyle('A4')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('A5:C5');
        $sheet->setCellValue('A5', '收货单位：');
        $sheet->getStyle('A5')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('A6:C8');
        $sheet->setCellValue('A6', '收货地址：');
        $sheet->getStyle('A6')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT)
            ->setVertical(Alignment::VERTICAL_CENTER);

        $sheet->mergeCells('D4:E8');
        $sheet->setCellValue('D4', '报价单');
        $sheet->getStyle('D4')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)
            ->setVertical(Alignment::VERTICAL_CENTER);


        $sheet->mergeCells('F4:H4');
        $sheet->setCellValue('F4', '电话：');
        $sheet->getStyle('F4')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('F5:H5');
        $sheet->setCellValue('F5', '合同号：');
        $sheet->getStyle('F5')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('F6:H6');
        $sheet->setCellValue('F6', '单据编号：');
        $sheet->getStyle('F6')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('F7:H7');
        $sheet->setCellValue('F7', '联系人：');
        $sheet->getStyle('F7')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('F8:H8');
        $sheet->setCellValue('F8', '电话：');
        $sheet->getStyle('F8')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        // 3. 设置表头
        $sheet->setCellValue('A9', '型号')
            ->setCellValue('B9', '名称')
            ->setCellValue('C9', '规格')
            ->setCellValue('D9', '单位')
            ->setCellValue('E9', '数量')
            ->setCellValue('F9', '单价')
            ->setCellValue('G9', '金额')
            ->setCellValue('H9', '备注');

        // 4. 填充数据
        $row = 10;
        $totalprice = 0;
        foreach ($data as $item) {
            $sheet->setCellValue('A' . $row, $item['model']);
            $sheet->setCellValue('B' . $row, $item['name']);
            $sheet->setCellValue('C' . $row, $item['sku']);
            $sheet->setCellValue('D' . $row, $item['quantity_unit']);
            $sheet->setCellValue('E' . $row, $item['number']);
            $price = $type ? $item['price'] : $item['old_price'];
            $sheet->setCellValue('F' . $row, $price);
            $total = $price * $item['number'];
            $sheet->setCellValue('G' . $row, $total);
            $totalprice += $total;
            $row++;
        }
        $sheet->getStyle('A9:H' . $row - 1)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)
            ->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->mergeCells('A' . $row . ':C' . $row);
        $sheet->setCellValue('A' . $row, '合计：' . $total);
        $sheet->getStyle('A' . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

        $sheet->mergeCells('H10:H' . $row);
        $sheet->getStyle('H10')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        $sheet->mergeCells('A' . $row + 1 . ':H' . $row + 1);
        $sheet->getStyle('A' . $row + 1)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
        $sheet->setCellValue('A' . $row + 1, '备注：');
        // 5. 设置自动列宽
        foreach (range('A', 'H') as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }
        //样式变量
        $style = [
            //设置边框线样式
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => 'FF000000'],
                ]
            ],
        ];
        $sheet->getStyle('A1:H' . $row + 1)->applyFromArray($style);
        $filename = 'order_' . date('YmdHis') . '.xlsx';
        $savePath = config('filesystem.disks.local.root') . '/quotations/';

        // 确保目录存在
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true);
        }

        // 写入文件
        $writer = new Xlsx($spreadsheet);
        $writer->save($savePath . $filename);
        return $this->json(['url' => gethost() . '/addons/xm_mallv3/samos/runtime/storage/quotations/' . $filename]);
    }
    public function total()
    {
        $cart = new Cart;
        $total = $cart->count_cart_total();
        $data['total'] = $total;
        return $this->json(['data' => $data]);
    }

    public function del()
    {
        $id = input('post.id');
        $ids = input('post.ids');
        if (!empty($id)) {
            $result = Cart::where('id', $id)->delete();
        } elseif (!empty($ids)) {
            $inids = explode(',', $ids);
            Cart::where(['id' => $inids])->delete();
        }
        if ($result) {
            $message = '删除成功';
        } else {
            $message = '删除失败';
        }
        return $this->json(['message' => $message, 'data' => $data]);
    }

    public function add()
    {

        $cart = new Cart;
        $param['goods_id'] = input('post.goodsId');
        $param['sku'] = input('post.sku');
        $param['quantity'] = input('post.quantity');

        if (empty($param['type'])) {
            $param['type'] = 'money';
        }

        $Membermob = new Member;

        $memberinfo = $Membermob->getUserByWechat();

        $param['uid'] = $memberinfo['id'];

        $param['weid'] = weid();

        //加入购物车	
        if ($cart->add($param)) {
            //计算购物车商品数量
            $total = $cart->count_cart_total();
        } else {
            $errno = 1;
            $message = '更新失败';
        }

        $data['total'] = $total;

        return $this->json(['message' => $message, 'errno' => $errno, 'data' => $data]);
    }

    public function check()
    {
        $goodsmob = new Goods;
        $id = input('post.goodsId');
        $sku = input('post.sku');
        $number = input('post.number');


        $goodsPrice = $goodsmob->cartGoods(['id' => $id, 'sku' => $sku, 'quantity' => $number]);

        $data['price'] = $goodsPrice['price'];
        $data['total'] = $goodsPrice['total'];
        $data['points'] = $goodsPrice['total_return_points'];
        $data['stores'] = $goodsPrice['stores'];
        $data['sku'] = $goodsPrice['sku'];

        return $this->json(['data' => $data]);
    }

    public function quantity()
    {
        $errno = 0;
        $goodsmob = new Goods;
        $id = input('post.id');
        $uptype = input('post.uptype');
        $quantity = input('post.quantity');

        if ($uptype == 'plus') {
            $uptype =  'jia';
        }
        if ($uptype == 'reduce') {
            $uptype =  'jian';
        }

        if (!empty($id)) {
            $cart = Cart::find($id);
            if ($uptype == 'jia') {
                $sku = $cart->sku;
                $goodsid = $cart->goods_id;
                $goods = $goodsmob->cartGoods(['id' => $goodsid, 'sku' => $sku]);
                if (intval($quantity) < 1) {
                    $quantity = intval($cart->quantity) + 1;
                }
                if (intval($quantity) > intval($goods['stores'])) {
                    $errno = 1;
                    $message = '商品库不足';

                    return $this->json(['message' => $message, 'errno' => $errno, 'data' => $data]);
                }
            } elseif ($uptype == 'jian') {

                if (intval($quantity) < 1) {
                    $quantity = intval($cart->quantity) - 1;
                }
                if (intval(jian) < 1) {
                    //数量小于1删除商品
                    Cart::where('id', $id)->delete();
                }
            }
            $result = Cart::update(['quantity' => $quantity, 'id' => $id]);
        }
        return $this->json(['message' => $message, 'errno' => $errno, 'data' => $data]);
    }
}
